---
import Header from '@components/Header.astro';
import Footer from '@components/Footer.astro';
import { siteConfig } from '@config/site';

interface Props {
	title?: string;
	showHeader?: boolean;
}

const { title, showHeader = true } = Astro.props;
const pageTitle = title ? `${title} - ${siteConfig.name}` : siteConfig.name;
---

<!doctype html>
<html lang={siteConfig.language}>
	<head>
		<meta charset="UTF-8" />
		<meta name="description" content={siteConfig.description} />
		<meta name="viewport" content="width=device-width" />
		<meta name="author" content={siteConfig.author} />
		<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
		<meta name="generator" content={Astro.generator} />
		<title>{pageTitle}</title>
	</head>
	<body class="min-h-screen flex flex-col bg-gray-50 dark:bg-gray-900 transition-colors duration-300">
		{showHeader && <Header />}
		<main class={`flex-grow ${!showHeader ? 'p-0' : 'max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8'}`}>
			<slot />
		</main>
		<Footer />
	</body>
</html>

<script>
  import Alpine from 'alpinejs'
  import intersect from '@alpinejs/intersect'
  
  Alpine.plugin(intersect)

  // 添加全局主题状态
  document.addEventListener('alpine:init', () => {
    Alpine.store('theme', {
      isDark: localStorage.theme === 'dark' || 
        (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches),

      init() {
        if (this.isDark) {
          document.documentElement.classList.add('dark');
        }
      },

      toggle() {
        this.isDark = !this.isDark;
        if (this.isDark) {
          document.documentElement.classList.add('dark');
          localStorage.theme = 'dark';
        } else {
          document.documentElement.classList.remove('dark');
          localStorage.theme = 'light';
        }
      }
    });

    // 初始化主题
    Alpine.store('theme').init();
  });

  // 监听系统主题变化
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
    if (!('theme' in localStorage)) {
      const isDark = e.matches;
      if (isDark) {
        document.documentElement.classList.add('dark');
      } else {
        document.documentElement.classList.remove('dark');
      }
      Alpine.store('theme').isDark = isDark;
    }
  });

</script>

<style is:global>
	[x-cloak] { display: none !important; }
	
	html.dark {
		color-scheme: dark;
	}

	body {
		transition: background-color 0.3s ease;
	}
</style>
